package cn.stronglink.assetmanage.business.check.detail;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.SpinnerShowUtil;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.BaseDataUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import util.StringUtils;

/**
 * 资产详情页面
 */
public class CheckDetailActivity extends BaseActivity implements View.OnClickListener, IScanerListener,
        View.OnTouchListener {
    ;
    private Spinner sp_check_location, sp_brand_name, sp_check_asset_class,
            sp_check_model;
    private EditText tv_check_asset_name, tv_check_asset_no, tv_check_sn_no, tv_check_rfid_no;
    private Button bbtn_save_detail_data, btn_add_check_cancel;
    private int ScanDataType = 0;
    private TimerInfraraedScaner scaner;
    private Asset asset;
    private long assetNo;
    private String roomId = "", typeId = "", brandId = "", modelId = "";
    private ArrayAdapter<Model> modelArrayAdapter;
    private String btimapPath;
    private String orderNo;
    private ImageView img_btn_cancel, img_check_camera, img_check_album;
    private int PICTURE_URL = 1000;
    private int PICTURE_LOCAL = 1001;
    private Bitmap bitmap;
    private boolean isStartCamera = false;
    private Dialog mCustomProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_detail);
        initDataAndView();
    }

    private void initDataAndView() {
        initView();
        initData();
    }

    private void initView() {
        tv_check_asset_name = findViewById(R.id.tv_check_asset_name);
        sp_check_location = findViewById(R.id.sp_check_location);
        sp_brand_name = findViewById(R.id.sp_brand_name);
        sp_check_asset_class = findViewById(R.id.sp_check_asset_class);
        sp_check_model = findViewById(R.id.sp_check_model);
        tv_check_asset_no = findViewById(R.id.tv_check_asset_no);
        tv_check_sn_no = findViewById(R.id.tv_check_sn_no);
        tv_check_rfid_no = findViewById(R.id.tv_check_rfid_no);
        bbtn_save_detail_data = findViewById(R.id.btn_save_detail);
        btn_add_check_cancel = findViewById(R.id.btn_add_check_cancel);
        img_btn_cancel = findViewById(R.id.img_btn_detail_cancel);
        img_check_camera = findViewById(R.id.img_check_camera);
        img_check_album = findViewById(R.id.img_check_album);
        tv_check_asset_no.setOnTouchListener(this);
        tv_check_sn_no.setOnTouchListener(this);
        tv_check_rfid_no.setOnTouchListener(this);
        bbtn_save_detail_data.setOnClickListener(this);
        scaner = new TimerInfraraedScaner(this);
        scaner.setScanerListener(this);
        btn_add_check_cancel.setOnClickListener(this);
        img_btn_cancel.setOnClickListener(this);
        img_check_album.setOnClickListener(this);
        img_check_camera.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        assetNo = intent.getLongExtra(Constants.CHECK_IN_DETAIL_NO, 0);
        asset = CheckDataUtil.getAssetByAssetId(Long.valueOf(assetNo));
        List<Model> modelList = BaseDataUtil.getModelList();
        List<Type> typeList = BaseDataUtil.getTypeList();
        List<Brand> brandList = BaseDataUtil.getBrandList();
        List<Room> roomList = BaseDataUtil.getRoomList();
        modelArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, modelList);
        ArrayAdapter<Type> typeArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, typeList);
        ArrayAdapter<Brand> brandArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, brandList);
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, roomList);
        sp_check_location.setAdapter(roomArrayAdapter);
        sp_check_model.setAdapter(modelArrayAdapter);
        sp_brand_name.setAdapter(brandArrayAdapter);
        sp_check_asset_class.setAdapter(typeArrayAdapter);
        sp_check_model.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    Model model = (Model) sp_check_model.getSelectedItem();
                    modelId = model.getId_();
                    asset.setModelName(model.getName());
                    asset.setModelId_(modelId);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_check_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    Room room = (Room) sp_check_location.getSelectedItem();
                    roomId = room.getId_();
                    asset.setRoomName(room.getName());
                    asset.setRoomId_(roomId);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_brand_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Brand brand = (Brand) sp_brand_name.getSelectedItem();
                brandId = brand.getId_();
                if (position != 0) {
                    asset.setBrandName(brand.getName());
                    asset.setBrandId_(brandId);
                }
                setModeData();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_check_asset_class.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Type type = (Type) sp_check_asset_class.getSelectedItem();
                typeId = type.getId_();
                if (position != 0) {
                    asset.setTypeName(type.getName());
                    asset.setTypeId_(typeId);
                }
                setModeData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        if (!isStartCamera) {
            showDetailAsset();
            isStartCamera = false;
        }
    }

    private void showDetailAsset() {
        if (asset != null) {
            orderNo = asset.getOrderNo();
            tv_check_asset_name.setText(asset.getAssetName());
            tv_check_asset_no.setText(asset.getAssetNo());
            tv_check_sn_no.setText(asset.getSerialNo());
            tv_check_rfid_no.setText(asset.getRfidNo());
            SpinnerShowUtil.setSpinnerItemSelectedByValue(sp_check_location, asset.getRoomName());
            SpinnerShowUtil.setSpinnerItemSelectedByValue(sp_brand_name, asset.getBrandName());
            SpinnerShowUtil.setSpinnerItemSelectedByValue(sp_check_asset_class, asset.getTypeName());
            SpinnerShowUtil.setSpinnerItemSelectedByValue(sp_check_model, asset.getModelName());
            String picPath = asset.getPictureUri();
            if (picPath != null && !"".equals(picPath)) {
                //设置图片
                img_btn_cancel.setImageBitmap(ImageUtils.getSDCardImg(picPath));
                btimapPath = picPath;
            }

        }
    }

    private void setModeData() {
        List<Model> modelList = BaseDataUtil.queryModelByBrandAndType(brandId, typeId);
        if (modelList != null) {
            modelArrayAdapter.clear();
            modelArrayAdapter.addAll(modelList);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.btn_save_detail:
                if (tv_check_asset_name.getText().toString().isEmpty()) {
                    ToastUtil.toastShort("资产名称不能为空");
                    return;
                }
                //保存详情
                if (tv_check_sn_no.getText().toString().isEmpty()) {
                    ToastUtil.toastShort("SN号不能为空");
                    return;
                }
                if (tv_check_asset_no.getText().toString().isEmpty()) {
                    ToastUtil.toastShort("资产编号不能为空");
                    return;
                }
                saveData();
                ToastUtil.toastShort("保存成功");
                finish();
                break;
            case R.id.btn_add_check_cancel:
                //取消
                finish();
                break;
            case R.id.img_check_camera:
                //调用相机
                saveData();
                startActivityForPicture(PICTURE_URL);
                break;
            case R.id.img_check_album:
                //调用相册
                saveData();
                startActivityForPicture(PICTURE_LOCAL);
                break;
            default:
                break;
        }
    }


    private void saveData() {
        mCustomProgressDialog = CustomProgressDialog.createLoadingDialog(this
                , "正在保存图片");
        mCustomProgressDialog.setCancelable(false);
        mCustomProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getAssetInfo();
                CheckDataUtil.saveAsset(asset);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mCustomProgressDialog != null) {
                            mCustomProgressDialog.cancel();
                        }
                    }
                });
            }
        }).start();

    }

    private void startActivityForPicture(int requestCode) {
        isStartCamera = true;
        if (requestCode == 1000) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //启动相机程序
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            startActivityForResult(intent, requestCode);
        } else {
            Intent intent = null;
            if (Build.VERSION.SDK_INT < 19) {
                intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
            } else {
                intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            }
            startActivityForResult(intent, requestCode);
        }
    }

    private void getAssetInfo() {
        asset.setOrderNo(orderNo);
        asset.setIsUpdate(true);
        asset.setBrandId_(brandId);
        asset.setRoomId_(roomId);
        asset.setModelId_(modelId);
        asset.setTypeId_(typeId);
        asset.setUpdateTime(CheckDataUtil.updateTime());
        asset.setRfidNo(StringUtils.replaceBlank(tv_check_rfid_no.getText().toString()));
        asset.setAssetNo(StringUtils.replaceBlank(tv_check_asset_no.getText().toString()));
        asset.setSerialNo(StringUtils.replaceBlank(tv_check_sn_no.getText().toString()));
        Long userId = User.getInstance().getUser_id();
        if (userId != null) {
            asset.setCreateBy(userId);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
        String time = format.format(new Date());
        asset.setAssetName(StringUtils.replaceBlank(tv_check_asset_name.getText().toString()));
        asset.setCreateTime(time);
        if (btimapPath != null) {
            asset.setPictureUri(btimapPath);
            asset.setImgPath(ImageUtils.imageToBase64(btimapPath));
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(1);
//        initDataAndView();
    }

    @Override
    public void onScaning(List<String> data) {
        if (data != null && data.size() > 0) {
            String resultData = data.get(data.size() - 1).replace(" ", "");
            switch (ScanDataType) {
                case 1:
                    tv_check_asset_no.setText(resultData);
                    break;
                case 2:
                    tv_check_sn_no.setText(resultData);
                    break;
                case 3:
                    tv_check_rfid_no.setText(resultData);
                    break;
                default:
                    break;
            }
            Log.e("rfid扫描", "二维码" + resultData);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case 1000:
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            // 获取相机返回的数据，并转换为Bitmap图片格式
                            bitmap = (Bitmap) bundle.get("data");
                            if (bitmap != null) {
                                btimapPath = ImageUtils.saveImageToLocal(bitmap);
                                img_btn_cancel.setImageBitmap(bitmap);
                            }
                        }
                        break;
                    case 1001:
                        if (data != null) {
                            Uri selectedImage = data.getData();
                            String[] filePathColumns = {MediaStore.Images.Media.DATA};
                            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                            c.moveToFirst();
                            int columnIndex = c.getColumnIndex(filePathColumns[0]);
                            btimapPath = c.getString(columnIndex);
                            showImage(btimapPath);
                            c.close();
                        }
                        break;
                    default:
                        break;
                }

                break;
            case RESULT_CANCELED:

                break;
            default:
                break;
        }
    }

    //加载图片
    private void showImage(String imaePath) {
        if (imaePath != null) {
            Bitmap bitmapTemp = ImageUtils.getSDCardImg(imaePath);
            if (bitmapTemp != null) {
                Bitmap bitmapResult = ImageUtils.comp(bitmapTemp);
                img_btn_cancel.setImageBitmap(bitmapResult);
            } else {
                ToastUtil.toastShort("图片损坏，不能使用");
            }
        } else {
            ToastUtil.toastShort("图片损坏，不能使用");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scaner != null) {
            this.scaner.stop();
            this.scaner.destory();
        }
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                switch (v.getId()) {
                    case R.id.tv_check_asset_no:
                        // 资产编号扫描
                        ScanDataType = 1;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
                    case R.id.tv_check_sn_no:
                        //sn号扫描
                        ScanDataType = 2;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
                    case R.id.tv_check_rfid_no:
                        //rfid
                        ScanDataType = 3;
                        if (scaner == null) {
                            scaner = new TimerInfraraedScaner(this);
                            scaner.setScanerListener(this);
                        }
                        scaner.playSingle();
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
        return false;
    }
}
